#!/usr/bin/perl -w

#-------------------------------------------------------------------------------
# Author:  Marelie Davel (marelie.davel@gmail.com)
# Info:    Formats symbol data for D&R rule extraction
#-------------------------------------------------------------------------------

use strict;
use warnings;

#-------------------------------------------------------------------------------

sub print_usage() {
  print "Usage: reformat.pl <in:data> <out:defref_data> <out:defref_symbols>\n";
  print "       <in:data>             data in tab-delimited format (WF1, symbol, WF2)\n";
  print "       <out:defref_data>     data formatted for D&R training\n";
  print "       <out:defref_symbols>  symbols formatted for D&R training\n";
}

#-------------------------------------------------------------------------------

sub increase_symbol($) {
  my $num = shift @_;
  if ($num == ord("9")) {
    $num = ord("A");
  } elsif ($num == ord("Z")) {
    $num = ord("a");
  } else {
    $num++;
  }   
  #printf "INFO: new symbol %s\n",chr($num);
  return $num;
}

sub convert_defref($$$) {
  my ($inName,$outName, $symName) = @_;
  open my $in, '<:encoding(utf8)', $inName or die "Cannot open $inName";
  open my $out, '>:encoding(utf8)', $outName or die "Cannot open $outName";
  open my $symbols, '>:encoding(utf8)', $symName or die "Cannot open $symName";

  my %classInv=();
  my $largestClass = ord("0");
  my $id=0;
  while (<$in>) {
    chomp;
    my @parts = split /\t/;
    if (scalar @parts != 3) {
      die "Error: format error in input file: $_\n";
    }
    my $className = $parts[1];
    my $currentSymbol = "";
    if (!(exists $classInv{$className})) {
      #print "First time seen: $className\n";
      $largestClass = increase_symbol($largestClass);
      #printf "New class symbol: %s\n", chr($largestClass);
      $classInv{$className}=$largestClass;
      $currentSymbol = chr($largestClass);
    } else {
      #print "Seen before: $className\n";
      $currentSymbol = chr($classInv{$className});
    }
    $id++;
    $parts[0] =~ s/ /#/g;		#Hardcoded symbols, remap 
    $parts[0] =~ s/-/%/g;
    $parts[0] =~ s/'/@/g;
    printf $out "%d;%s;#%s-d-\n",$id,$currentSymbol,$parts[0];
  }
  close $in;

  foreach my $c (sort{$classInv{$a}<=>$classInv{$b}} keys %classInv) {
    printf $symbols "%s\t%s\n",$c,chr($classInv{$c});
  }
  close $out;
}

#--------------------------------------------------------

if (scalar @ARGV == 3) {
  convert_defref($ARGV[0],$ARGV[1],$ARGV[2]);
} else {
  print_usage();
  exit;
}

#--------------------------------------------------------

